package ollama.ai.two.service.impl;

import lombok.extern.slf4j.Slf4j;
import ollama.ai.two.service.TextService;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;


import java.util.List;

/**
 * @Auther:Liu
 * @Testname:TextServiceImpl
 * @Date:2025/9/23 19:05
 */
@Service
@Slf4j
public class TextServiceImpl implements TextService {
    @jakarta.annotation.Resource
    private VectorStore vectorStore;

    /**
     * 存储数据到向量数据库
     *
     * @param textResource
     */
    @Override
    public void textAdd(Resource textResource) {
        //1.读取文本资源并获取文档
        TextReader textReader = new TextReader(textResource);
        List<Document> documents = textReader.get();
        //2.按token拆分
        TokenTextSplitter splitter = new TokenTextSplitter();
        List<Document> split = splitter.split(documents);
        //3.将拆分后的数据存储到向量数据库中
        vectorStore.add(split);
    }

    @Override
    public void textDelete(String ids) {
        List<String> ids1 = List.of(ids);
        vectorStore.delete(ids1);
    }

    @Override
    public void textFind(String keyword) {
        String question = keyword;
        int top = 6;
        double threshold = 0.2;
        SearchRequest searchRequest = SearchRequest.builder()
                .query(question) // 问题
                .topK(top)  // 返回的条数
                .similarityThreshold(threshold)
                // 相似度阈值
                .build();
        List<Document> documents = vectorStore.similaritySearch(searchRequest);
        documents.forEach(e -> log.info("e:{}", e));
    }

    @Override
    public void textAddMax(String text) {
        List<Document> documents = List.of(
                new Document(text)
        );
        vectorStore.add(documents);
    }

}
